import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# import os
# import time

def plot_trend_for_topic(topic, data, i):
    # 过滤数据
    topic_data = data[data['title'] == topic]

    # 按日期分组并计算点赞数或出现次数
    trend = topic_data.groupby('date').agg({
        'like': 'sum',
        'title': 'size'
    }).reset_index()

    # 绘制图表
    fig, ax1 = plt.subplots(figsize=(12, 8))

    # 绘制点赞数曲线
    sns.lineplot(data=trend, x='date', y='like', marker='o', ax=ax1, label='点赞数', color='b', linewidth=2.5)
    ax1.set_ylabel('点赞数', fontsize=16, color='b', fontweight='bold')
    ax1.tick_params(axis='y', labelsize=14, labelcolor='b')

    # 创建第二个纵轴
    ax2 = ax1.twinx()
    sns.lineplot(data=trend, x='date', y='title', marker='x', ax=ax2, label='出现次数', color='r', linewidth=2.5)
    ax2.set_ylabel('出现次数', fontsize=16, color='r', fontweight='bold')
    ax2.tick_params(axis='y', labelsize=14, labelcolor='r')

    # 设置标题和标签
    ax1.set_title(f'{topic} 热度趋势图', fontsize=20, fontweight='bold')
    ax1.set_xlabel('日期', fontsize=16, fontweight='bold')
    ax1.tick_params(axis='x', labelsize=14)

    # 图例
    ax1.legend(loc='upper left', fontsize=14)
    ax2.legend(loc='upper right', fontsize=14)

    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.xticks(rotation=45)
    plt.grid(True)
    plt.tight_layout()

    # 保存图表
    fig.savefig(f'../public/data/img/{i}_trend.png')  # 使用 fig 保存图表
    plt.close()

def topic_popularity_analysis():
    # 设置Seaborn样式
    sns.set(style="whitegrid")

    # 读取 Excel 文件
    file_path = '../public/data/tables/data_orin.xlsx'
    # 循环等待文件生成
    # while not os.path.exists(file_path):
    #     print(f"Waiting for {file_path} to be created...")
    #     time.sleep(1)  # 每隔1秒检查一次
    data = pd.read_excel(file_path)

    # 获取所有唯一的话题
    topics = data['title'].unique()

    # 创建一个函数来生成热度趋势图
    # 为每个话题生成图表
    counter = 0
    for topic in topics:
        counter += 1
        plot_trend_for_topic(topic, data, counter)

    print("所有话题的热度趋势图已生成。")

if __name__ == '__main__':
    topic_popularity_analysis()
